package com.nodecollege.cloud.common.model.vo;

import com.nodecollege.cloud.common.model.po.UpmsAppResource;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 应用资源树
 *
 * @author LC
 * @date 2019/12/17 19:59
 */
@Data
public class AppResourceTreeVO extends UpmsAppResource implements Comparable<AppResourceTreeVO> {
    /**
     * 子集
     */
    private List<AppResourceTreeVO> children;

    public AppResourceTreeVO() {
    }

    public AppResourceTreeVO(UpmsAppResource resource) {
        super.setAppResourceId(resource.getAppResourceId());
        super.setResourceCode(resource.getResourceCode());
        super.setResourceType(resource.getResourceType());
        super.setResourceName(resource.getResourceName());
        super.setNum(resource.getNum());
        super.setParentId(resource.getParentId());
        super.setState(resource.getState());
        super.setPath(resource.getPath());
        super.setApiId(resource.getApiId());
        super.setApplicationName(resource.getApplicationName());
        super.setControllerName(resource.getControllerName());
        super.setApiUrl(resource.getApiUrl());
        super.setOpenType(resource.getOpenType());
        super.setAppId(resource.getAppId());
    }

    public static List<AppResourceTreeVO> getAppResourceTree(List<UpmsAppResource> resourceList) {
        return getAppResourceTree(resourceList, 0L);
    }

    /**
     * 获取menuTree
     *
     * @return
     */
    public static List<AppResourceTreeVO> getAppResourceTree(List<UpmsAppResource> resourceList, Long pid) {
        List<AppResourceTreeVO> resourceTreeList = new ArrayList<>();
        Iterator<UpmsAppResource> resourceIterator = resourceList.iterator();
        while (resourceIterator.hasNext()) {
            UpmsAppResource menu = resourceIterator.next();
            if (menu.getParentId().equals(pid)) {
                resourceTreeList.add(new AppResourceTreeVO(menu));
                resourceIterator.remove();
            }
        }
        Collections.sort(resourceTreeList);
        for (AppResourceTreeVO resourceTreeVO : resourceTreeList) {
            resourceTreeVO.setChildren(getAppResourceTree(resourceList, resourceTreeVO.getAppResourceId()));
        }
        if (resourceTreeList.isEmpty()){
            return null;
        }
        return resourceTreeList;
    }

    @Override
    public int compareTo(AppResourceTreeVO o) {
        return this.getNum().compareTo(o.getNum());
    }
}
